//
//  HHPService.m
//  HHPLiveVideo
//
//  Created by 韩红坡 on 2016/12/16.
//  Copyright © 2016年 韩红坡. All rights reserved.
//

#import "HHPService.h"

#import <AFNetworkActivityIndicatorManager.h>
#import "MJExtension.h"
#import "HHPRequestCache.h"
#import "HHPMediatorManager+Login.h"

@interface HHPHTTPBlockDataHander ()

@property (nonatomic, strong) id (^block)(id, NSURLSessionTask *);

@end

@implementation HHPHTTPBlockDataHander

+ (instancetype)dataHandlerWithBlock:(id (^)(id, NSURLSessionTask *))block
{
    return [[self alloc] initWithBlock:block];
}

- (instancetype)initWithBlock:(id (^)(id, NSURLSessionTask *))block
{
    self = [super init];
    if (self) {
        self.block = block;
    }
    return self;
}

- (id)handleData:(id)data task:(NSURLSessionDataTask *)task
{
    if (self.block) {
        return self.block(data, task);
    } else {
        return data;
    }
}

@end

@interface HHPHTTPDataHandler ()

@property (nonatomic, assign) HHPHTTPDataHandlerType type;
@property (nonatomic, assign) Class modelClass;

@end

@implementation HHPHTTPDataHandler

+ (instancetype)dataHandlerWithType:(HHPHTTPDataHandlerType)type modelClass:(Class)modelClass
{
    return [[self alloc] initWithType:type modelClass:modelClass];
}

- (instancetype)initWithType:(HHPHTTPDataHandlerType)type modelClass:(Class)modelClass
{
    self = [super init];
    if (self) {
        self.type = type;
        self.modelClass = modelClass;
    }
    return self;
}

- (id)handleData:(id)data task:(NSURLSessionDataTask *)task
{
    if (![data isKindOfClass:[NSDictionary class]]) {
        return [self parseErrorWithMessage:@"返回结果必须是一个对象"];
    }
    
    NSDictionary *responseDict = data;
    NSNumber *codeNumber = responseDict[@"code"];
    if (!codeNumber) {
        return [self parseErrorWithMessage:@"返回的对象没有包含code字段"];
    }
    
    int code = codeNumber.intValue;
    id dataObject = responseDict[@"data"];
    
    
    if (code == 100) {
        return [self filterData:dataObject];
    } else {
        return [self filterError:responseDict];
    }
}

- (NSError *)filterError:(id)responseDict
{
    if (![responseDict isKindOfClass:[NSDictionary class]]) {
        return [self parseErrorWithMessage:@"返回的error必须是一个对象"];
    }
    
    NSNumber *codeNumber = responseDict[@"code"];
    NSString *message = responseDict[@"msg"] ? : @"加载失败";
    
    if (!codeNumber) {
        return [self parseErrorWithMessage:message];
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[@"code"] = codeNumber;
    userInfo[@"msg"] = message;
    userInfo[NSLocalizedDescriptionKey] = message;
    return [self serverErrorWithCode:codeNumber.integerValue userInfo:userInfo];
}

- (id)filterData:(id)object
{
    NSError *error;
    switch (self.type) {
        case HHPHTTPDataHandlerTypeAny:
            return object;
            
        case HHPHTTPDataHandlerTypeString:
            if ([object isKindOfClass:[NSDictionary class]]) {
                object = [[object allValues] firstObject];
            }
            return [object isKindOfClass:[NSString class]] ? object : [self parseErrorWithMessage:@"data必须是一个字符串"];
            
        case HHPHTTPDataHandlerTypeNumber:
            if ([object isKindOfClass:[NSDictionary class]]) {
                object = [[object allValues] firstObject];
            }
            return [object isKindOfClass:[NSNumber class]] ? object : [self parseErrorWithMessage:@"data必须是一个数字"];
            
        case HHPHTTPDataHandlerTypeDictionary:
            if (![object isKindOfClass:[NSDictionary class]]) {
                return [self parseErrorWithMessage:@"data必须是一个对象"];
            }

            object = [self.modelClass mj_objectWithKeyValues:object];
            return object ? : error;
            
        case HHPHTTPDataHandlerTypeArray:
            if ([object isKindOfClass:[NSDictionary class]]) {
                if (!([[object objectForKey:@"list"] isKindOfClass:[NSArray class]] || [[[object allValues] firstObject] isKindOfClass:[NSArray class]])) {
                    return [self parseErrorWithMessage:@"data必须是一个数组"];
                }
            } else if (![object isKindOfClass:[NSArray class]]) {
                return [self parseErrorWithMessage:@"data必须是一个数组"];
            }
            
            if ([object isKindOfClass:[NSDictionary class]]) {
                if ([object objectForKey:@"list"]) {
                    object = [object objectForKey:@"list"];
                } else {
                    object = [[object allValues] firstObject];
                    if (![object isKindOfClass:[NSArray class]]) {
                        return [self parseErrorWithMessage:@"data必须是一个数组"];
                    }
                }
            }
            
            object = [self.modelClass mj_objectArrayWithKeyValuesArray:object];
            return object ? : error;
            
        default:
            break;
    }
    return nil;
}

- (NSError *)parseErrorWithMessage:(NSString *)message
{
    return [NSError errorWithDomain:HHPServiceParseErrorDomain
                               code:NSIntegerMax
                           userInfo:@{NSLocalizedDescriptionKey:message}];
}

- (NSError *)serverErrorWithCode:(NSInteger)code userInfo:(NSDictionary *)userInfo
{
    return [NSError errorWithDomain:HHPServiceErrorDomain
                               code:code
                           userInfo:userInfo];
}

@end

@implementation HHPServiceErrorHandler

- (NSError *)handleError:(NSError *)error task:(NSURLSessionDataTask *)task
{
    if (([error.domain isEqualToString:HHPServiceErrorDomain] && error.code == 10024)) {
        // 弹出登录界面，并清空登录数据
        [[HHPMediatorManager sharedInstance] mediator_presentLoginViewController];
        
        return [NSError errorWithDomain:HHPServiceNetworkErrorDomain
                                   code:-1000
                               userInfo:@{
                                          NSLocalizedDescriptionKey:error.localizedDescription,
                                          HHPServiceOriginalErrorKey:error
                                          }];
    } else if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorNotConnectedToInternet) {
        return [NSError errorWithDomain:HHPServiceNetworkErrorDomain
                                   code:-1000
                               userInfo:@{
                                          NSLocalizedDescriptionKey:@"当前网络不可用，请检查网络设置",
                                          HHPServiceOriginalErrorKey:error
                                          }];
    } else if (![error.domain isEqualToString:HHPServiceErrorDomain]) {
        return [NSError errorWithDomain:HHPServiceNetworkErrorDomain
                                   code:-1000
                               userInfo:@{
                                          NSLocalizedDescriptionKey:@"加载失败",
                                          HHPServiceOriginalErrorKey:error
                                          }];
    } else {
        return error;
    }
}

@end

@implementation HHPHTTPEncryptHandler

- (NSMutableDictionary<NSString *,id> *)handleEncryptRequestParams:(NSMutableDictionary<NSString *,id> *)requestParams
{
    return [NSMutableDictionary dictionary];
}

@end

@implementation HHPHTTPRequestManager (AutoLoad)

+ (void)initialize
{
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    [HHPHTTPRequestManager manager].sessionManager = [self defaultSessionManager];
    [[HHPHTTPRequestManager manager] setDefaultOptionsBlock:^(HHPHTTPRequestOptions *options) {
        options.acceptContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        options.defaultHeaders = [self defaultHeaders];
        options.securityPolicy = [self defaultSecurityPolicy];
        options.dataHandler = [[HHPHTTPDataHandler alloc] initWithType:HHPHTTPDataHandlerTypeAny modelClass:nil];
        options.errorHandler = [[HHPServiceErrorHandler alloc] init];
        options.requestBodyType = HHPHTTPRequestBodyTypeHTTP;
    }];
}

+ (AFHTTPSessionManager *)defaultSessionManager
{
    static AFHTTPSessionManager *sessionManager;
    if (!sessionManager) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.URLCache = [HHPRequestCache sharedRequestCache];
        configuration.timeoutIntervalForResource = 15;
        configuration.timeoutIntervalForRequest = 15;
        sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    }
    return sessionManager;
}

+ (NSDictionary<NSString *, NSString *> *)defaultHeaders
{
    NSMutableDictionary *defaultHeaders = [NSMutableDictionary dictionary];
    
    //设备尺寸
//    NSString *rlValue = [NSString stringWithFormat:@"%.0f_%.0f",[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height];
//    [defaultHeaders setObject:rlValue forKey:@"rl"];
    //版本号
//    [defaultHeaders setObject:[UIApplication sharedApplication].appVersion forKey:@"version"];

    //手机系统版本
//    NSString *os = [[UIDevice currentDevice] systemVersion];
//    [defaultHeaders setObject:os forKey:@"os"];
    
    //渠道
//    [defaultHeaders setObject:@"appstore" forKey:@"ch"];
    
//    [defaultHeaders setObject:@"m1" forKey:@"client_id"];//平台标示
//    [defaultHeaders setObject:@"s1" forKey:@"client_secret"];//平台秘钥
//    [defaultHeaders setObject:@"password" forKey:@"grant_type"];
//    [defaultHeaders setObject:@"write" forKey:@"scope"];
    
    [defaultHeaders setObject:@"2.9.0" forKey:@"version"];
    [defaultHeaders setObject:@"60906990" forKey:@"useridx"];
    [defaultHeaders setObject:@"com.tiange.miaolive" forKey:@"bundleid"];
    [defaultHeaders setObject:@"app store" forKey:@"channelid"];
    [defaultHeaders setObject:@"ios" forKey:@"devicetype"];
    
    
    NSString *deviceId = [[UIDevice currentDevice] identifierForVendor].UUIDString;
    [defaultHeaders setObject:@"deviceid" forKey:deviceId];
    
    //登录taken
//    NSString *tokenString = @"";
    
//    tokenString = [NSString stringWithFormat:@"Bearer%@",tokenString];
//    
//    if (tokenString.length > 0) {
//        [defaultHeaders setObject:tokenString forKey:@"Authorization"];
//    }
    
    return defaultHeaders;
}

+ (AFSecurityPolicy *)defaultSecurityPolicy
{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = NO;
#ifdef DEBUG
    // 设置可以接收无效的证书
    securityPolicy.allowInvalidCertificates = YES;
#endif
    return securityPolicy;
}

@end

